<template>
  <div class="dashboard-container">
    <div class="dashboard-text">当前用户: {{ userName }}</div>
    <!-- <div class="dashboard-text">token: {{ token }}</div> -->
    <el-upload class="upload-demo" ref="upload" action="http://localhost:3007/api/uploads" :on-remove="handleRemove"
      :file-list="fileList" list-type="picture" :on-success="handleUploadSuccess" :on-error="handleUploadError" multiple
      :auto-upload="false" accept=".jpg, .png" :on-change="handleOnChange">
      <el-button size="small" type="primary">选择图片</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <el-button size="small" type="warning" @click="submitUpload">上传</el-button>

    {{successfulUploads}}  --  {{totalFiles}}
  </div>
</template>

<script>
  import {
    mapGetters
  } from 'vuex'

  export default {
    name: 'Dashboard',
    data() {
      return {
        fileList: [],
        filesToUpload: [],
        successfulUploads: 0,
        totalFiles: 0
      }
    },
    computed: {
      ...mapGetters([
        'userName'
      ])
    },
    methods: {
      submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handleOnChange(file, fileList) {
        // 只在文件列表发生变化时更新 filesToUpload,防止handleUploadSuccess时触发导致 this.totalFiles - 1
        if(file.status === "ready"){
          const isPic = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
          const isLt2M = file.size / 1024 / 1024 < 2;
          let hasUnAccept = false
          // console.log(file, fileList)
          if (!isPic || !isLt2M) {
            fileList.pop(); //移除掉最新的一个
            hasUnAccept = true;
          } else {
            this.filesToUpload = fileList.filter((f) => f.status === 'ready');
            this.totalFiles = this.filesToUpload.length;
          }
          if (hasUnAccept) {
            this.$message.error('已过滤掉不符合格式规定的文件');
          }
        }
      },
      handleUploadSuccess(res, file) {
        this.successfulUploads++

        if (this.successfulUploads ===  this.totalFiles) {
          this.$message.success('所有文件上传成功！');
        }
        // this.fileList.push()
      },
      handleUploadError(err, file, fileList) {
        console.log(err, file, fileList)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .dashboard {
    &-container {
      margin: 30px;
    }

    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
</style>
